package com.smitish.vueblog.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smitish.vueblog.common.dto.ModifyUserInfoDto;
import com.smitish.vueblog.common.lang.Result;
import com.smitish.vueblog.entity.Blog;
import com.smitish.vueblog.entity.Collection;
import com.smitish.vueblog.entity.Logs;
import com.smitish.vueblog.entity.User;
import com.smitish.vueblog.service.LogsService;
import com.smitish.vueblog.service.UserService;
import com.smitish.vueblog.util.OssUtil;
import com.smitish.vueblog.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Smitish
 * @since 2020-11-30
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    @Autowired
    LogsService logsService;

    @Autowired
    OssUtil ossUtil;


    /**
     * 获取用户基本信息
     *
     * @param id 请求的用户ID
     * @return 返回个人基本信息
     */
    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        User user = userService.getById(id);
        Assert.notNull(user, "用户不存在");
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("description", user.getDescription()).map());
    }

    /**
     * 更新用户信息
     *
     * @param modifyUserInfoDto 修改用户信息 新定义的实体类
     * @return 返回修改结果 并重新通知前端更新 之前缓存的数据
     */
    @RequiresAuthentication
    @PostMapping("/modifyInfo")
    public Result modifyInfo(@Validated @RequestBody ModifyUserInfoDto modifyUserInfoDto) {
        Map<String, Object> map = new HashMap<>();
        Long uid = ShiroUtil.getProfile().getId();
        // 判断邮箱除自身外是否有重复的
        User userInSQL = userService.getOne(new QueryWrapper<User>()
                .eq("email", modifyUserInfoDto.getEmail())
                .notIn("id", uid));
        if (userInSQL != null) {
            return Result.fail("邮箱已存在");
        } else {
            boolean flag = userService.updateUserInfo(modifyUserInfoDto, ShiroUtil.getProfile().getId());
            if (flag) {
                User user = userService.getById(uid);
                Logs logs = new Logs();
                logs.setUserId(ShiroUtil.getProfile().getId());
                logs.setLogContent("修改了个人信息");
                logsService.saveOrUpdate(logs);
                return Result.success(MapUtil.builder()
                        .put("id", user.getId())
                        .put("username", user.getUsername())
                        .put("avatar", user.getAvatar())
                        .put("email", user.getEmail())
                        .put("description", user.getDescription()).map()
                );
            } else {
                return Result.fail("修改个人信息失败");
            }
        }
    }


    @RequiresAuthentication
    @PostMapping("/uploadAvatar")
    public Map<String, Object> fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String url = ossUtil.uploadFile(file); //调用OSS工具类
            User user = userService.getById(ShiroUtil.getProfile().getId());
            user.setAvatar(url);
            boolean b = userService.saveOrUpdate(user);
            Map<String, Object> returnBody = new HashMap<>();
            Map<String, Object> returnMap = new HashMap<>();
            if (b) {
                returnMap.put("id", user.getId());
                returnMap.put("username", user.getUsername());
                returnMap.put("avatar", user.getAvatar());
                returnMap.put("email", user.getEmail());
                returnMap.put("description", user.getDescription());
                returnBody.put("data", returnMap);
                returnBody.put("code", "200");
                returnBody.put("msg", "上传成功");
                return returnBody;
            }
            returnBody.put("data", null);
            returnBody.put("code", "400");
            returnBody.put("msg", "上传失败");
            return returnBody;
        } catch (Exception e) {
            Map<String, Object> returnbody = new HashMap<>();
            returnbody.put("data", null);
            returnbody.put("code", "400");
            returnbody.put("message", "上传失败");
            return returnbody;
        }
    }

}
